<template>
  <!-- 搜索 -->
  <SeachInput placeholder="搜索" width="100%" v-model="searchValue"></SeachInput>
  <!-- 树形结构 -->
  <div class="tree-box mt-[25px]">
    <a-tree
      :checkable="true"
      disabled
      :checked-strategy="'child'"
      v-model:checked-keys="checkedKeys"
      :data="treeList"
      @check="onCheck"
    />
    <a-empty :description="'暂未搜索到相关联的数据'" v-if="treeList.length === 0" />
  </div>
</template>

<script setup lang="ts">
import { ref, inject, watch, onMounted } from 'vue';
import { getListEvent } from './values';

const isEdit = inject('isEdit');
const treeData = ref<any>([]);
const treeList = ref<any>([]);
const defaultCheckedKeys = inject('defaultCheckedKeys');
const searchValue = ref('');
const checkedKeys = ref(defaultCheckedKeys);

// 监听 searchValue 的变化并更新 treeList
watch(searchValue, (newValue) => {
  if (!newValue) {
    treeList.value = treeData.value;
  } else {
    treeList.value = searchData(newValue);
  }
});
/*  搜索树形数据 */
const searchData = (value: string) => {
  const loop = (data) => {
    const result = [] as any;
    data.forEach((item) => {
      if (item.title.toLowerCase().indexOf(value.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
        }
      }
    });
    return result;
  };
  return loop(treeList.value);
};

const onCheck = (checkedKeys: string[]) => {
  console.log('checkedKeys', checkedKeys);
};

/* 修改树形数据所有节点的disabled属性 */
const changeTreeDisabled = (treeList: any[], disabled: boolean) => {
  treeList.forEach((item) => {
    item.disabled = disabled;
    if (item.children) {
      changeTreeDisabled(item.children, disabled);
    }
  });
};

watch(
  isEdit,
  (v) => {
    if (v) {
      changeTreeDisabled(treeList.value, false);
    } else {
      changeTreeDisabled(treeList.value, true);
    }
  },
  {
    immediate: true
  }
);
onMounted(async () => {
  let res = await getListEvent();
  treeList.value = res;
  treeData.value = res;
});
</script>

<style lang="less" scope></style>
